<template>
  <div>
    <form-content
      :rules="formItems2Rules"
      :form-items="formItems"
      :beforeSubmit="beforeSubmit"
      :submitApi="submitApi"
      :afterSubmit="afterSubmit"
      :formStateInit="detail"
      :preview="preview"
      @formChange="formChange"
    >
      <!-- <template #other="{ item, formState }">
        <div>
          <a-input v-model:value="formState[item.name]"></a-input>
        </div>
      </template> -->
    </form-content>
  </div>
</template>

<script>
import moment from 'moment';
import { ref, toRefs, reactive } from 'vue';
import {useRouter} from 'vue-router';
import { message } from 'ant-design-vue';
import { formItems, formItems2Rules } from './config';
import { add, info, update } from '../api';

export default {
  data() {
    return {
      formItems,
      formItems2Rules,
    };
  },
  setup(props, context) {
    const router = useRouter();
    const {query, name: routeName} = router.currentRoute.value;
    const state = reactive({
      preview: routeName.includes('detail'),
      detail: {}
    })
    const afterSubmit = (res) => {
      res.code == 0 && message.success('提交成功');
      router.back()
    };
    const beforeSubmit = (data) => {
      data.banner_img = data.banner_img[0]
      return data;
    };

    const formChange = (item, formState, formItems) => {
      if (item.name == 'jump_type') {
        // formItems.forEach(val => {
        //   if (val.name == 'url') {
        //     val.hidden = formState.jump_type != 1
        //   }
        // })
      }
    }

    if (query.id) {
      info({id: Number(query.id)}).then(res => {
        const {data} = res;
        data.banner_img = [data.banner_img]
        if(data.start_at_s && data.end_at_s) {
          data.dateRange = [moment(data.start_at_s), moment(data.end_at_s)]
        }
        state.detail = data;
      })
    }

    const submitApi = (p) => {
      p.id = query.id ? Number(query.id) : query.id;
      return query.id ? update(p) : add(p);
    }

    return {
      ...toRefs(state),
      submitApi,
      beforeSubmit,
      afterSubmit,
      formChange,
    };
  },
};
</script>
